package servlet;

import pojo.Book;
import pojo.Category;
import service.BookService;
import service.impl.BookServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Tiler on 2020/11/6
 */
public class SetOneBook extends HttpServlet {
    private BookService bookService = new BookServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");

        Integer bookId = Integer.parseInt(req.getParameter("id"));
        Integer publisherId = Integer.parseInt(req.getParameter("publisher"));
        String[] categories = req.getParameterValues("category");

        List<Category> list = new ArrayList<>();

        //将分类id转换为分类对象列表
        if (categories != null && categories.length > 0) {
            for (String c : categories) {
                Category category = new Category();
                category.setCategoryId(Integer.parseInt(c));

                list.add(category);
            }
        }
        Book book = new Book();
        book.setBookId(bookId);
        book.setBookName(req.getParameter("bookName"));
        book.setImage(req.getParameter("image"));
        book.setPublisherId(publisherId);
        book.setCategories(list);

        if (bookService.setOneBook(book) > 0) {
            req.setAttribute("message", "修改成功");
        }
        else {
            req.setAttribute("message", "修改失败");
        }

        req.getRequestDispatcher("get_message.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
